/*
 *Copyright © 2015 zhaorongbao
 *招融宝
 *http://zhaorongbao.com
 *All rights reserved.
 */
package com.hanhai.zrb.api.biz.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.hanhai.zrb.api.biz.dao.mybatis.SequenceDao;
import com.hanhai.zrb.api.biz.service.SequenceService;

@Service("sequenceService")
public class SequenceServiceImpl implements SequenceService {
	@Resource
	private SequenceDao sequenceDao;

	// 强行开启一个新的事务
	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public Long getNextBySequenceName(String sequenceName) {
		Long cur = sequenceDao.getCurrentValue(sequenceName);
		sequenceDao.update(sequenceName);
		Long next = cur + 1;
		return next;
	}

	// 强行开启一个新的事务
	@Transactional( propagation = Propagation.REQUIRES_NEW)
	public Long getNextBySequenceName(String sequenceName, Long maxId) {
		Long cur = sequenceDao.getCurrentValue(sequenceName);
		sequenceDao.update(sequenceName);
		Long next = cur + 1;
		if (next > maxId) {
			sequenceDao.reset(sequenceName);
			return 1L;
		}
		return next;
	}

	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public Long getBorrowerBySequenceName(String name) {
		Long cur = sequenceDao.getCurrentValue(name);
		sequenceDao.update(name);
		Long next = cur + 1;
		return next;
	}
}
